<template>
  <div class="merchant-rating">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商家评分与信用管理</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="商家类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择商家类型"
            clearable
          >
            <el-option label="景点" value="scenic" />
            <el-option label="酒店" value="hotel" />
            <el-option label="餐饮" value="restaurant" />
            <el-option label="购物" value="shopping" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用等级">
          <el-select
            v-model="searchForm.creditLevel"
            placeholder="请选择信用等级"
            clearable
          >
            <el-option label="优秀" value="excellent" />
            <el-option label="良好" value="good" />
            <el-option label="一般" value="normal" />
            <el-option label="较差" value="poor" />
            <el-option label="风险" value="risk" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 评分统计 -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6" v-for="(stat, index) in ratingStats" :key="index">
          <el-card class="statistics-card" shadow="hover">
            <div class="statistics-content">
              <div
                class="statistics-icon"
                :style="{ backgroundColor: stat.color }"
              >
                <i :class="stat.icon"></i>
              </div>
              <div class="statistics-info">
                <div class="label">{{ stat.label }}</div>
                <div class="value">{{ stat.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 商家列表 -->
      <el-table :data="merchantList" border v-loading="loading">
        <template #header>
          <div class="table-header-operations">
            <el-button-group>
              <el-button
                :type="sortOrder === 'asc' ? 'primary' : 'default'"
                @click="toggleSortOrder('asc')"
                size="small"
              >
                正序
              </el-button>
              <el-button
                :type="sortOrder === 'desc' ? 'primary' : 'default'"
                @click="toggleSortOrder('desc')"
                size="small"
              >
                倒序
              </el-button>
            </el-button-group>
          </div>
        </template>
        <el-table-column type="expand">
          <template #default="props">
            <el-form label-position="left" inline class="rating-detail">
              <el-form-item label="服务质量评分">
                <el-progress
                  :percentage="props.row.serviceScore"
                  :color="getScoreColor(props.row.serviceScore)"
                />
              </el-form-item>
              <el-form-item label="商品质量评分">
                <el-progress
                  :percentage="props.row.productScore"
                  :color="getScoreColor(props.row.productScore)"
                />
              </el-form-item>
              <el-form-item label="环境卫生评分">
                <el-progress
                  :percentage="props.row.environmentScore"
                  :color="getScoreColor(props.row.environmentScore)"
                />
              </el-form-item>
              <el-form-item label="价格合理性">
                <el-progress
                  :percentage="props.row.priceScore"
                  :color="getScoreColor(props.row.priceScore)"
                />
              </el-form-item>
              <el-form-item label="用户好评率">
                <el-progress
                  :percentage="props.row.userRating"
                  :color="getScoreColor(props.row.userRating)"
                />
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商家名称" min-width="180" />
        <el-table-column prop="type" label="商家类型" width="100">
          <template #default="scope">
            <el-tag :type="getMerchantTypeTag(scope.row.type)">
              {{ getMerchantTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="overallScore" label="综合评分" width="120">
          <template #default="scope">
            <el-rate
              v-model="scope.row.overallScore"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="creditScore" label="信用评分" width="120">
          <template #default="scope">
            <span
              :style="{ color: getCreditScoreColor(scope.row.creditScore) }"
            >
              {{ scope.row.creditScore }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="creditLevel" label="信用等级" width="100">
          <template #default="scope">
            <el-tag :type="getCreditLevelTag(scope.row.creditLevel)">
              {{ getCreditLevelLabel(scope.row.creditLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningCount" label="警告次数" width="100" />
        <el-table-column prop="complaintRate" label="投诉率" width="100">
          <template #default="scope"> {{ scope.row.complaintRate }}% </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" link @click="handleRating(scope.row)">
                评分调整
              </el-button>
              <el-button type="warning" link @click="handleWarning(scope.row)">
                发送警告
              </el-button>
              <el-button
                type="danger"
                link
                @click="handlePunishment(scope.row)"
              >
                处罚
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <!-- 添加空状态模板 -->
        <template #empty>
          <el-empty 
            description="暂无商家评分数据" 
            :image-size="200"
          >
            <div class="empty-text">还没有任何商家评分信息</div>
            <div class="empty-subtext">添加商家并收集用户评价后，这里将显示评分数据</div>
            <el-button type="primary" @click="fetchMerchantList" class="mt-4">刷新数据</el-button>
          </el-empty>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评分调整对话框 -->
    <el-dialog
      v-model="ratingDialogVisible"
      title="评分调整"
      width="500px"
      :modal-append-to-body="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      class="rating-dialog"
      destroy-on-close
    >
      <el-scrollbar height="400px">
        <el-form
          ref="ratingFormRef"
          :model="ratingForm"
          :rules="ratingFormRules"
          label-width="100px"
        >
          <el-form-item label="服务质量评分" prop="serviceScore">
            <el-slider
              v-model="ratingForm.serviceScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="商品质量评分" prop="productScore">
            <el-slider
              v-model="ratingForm.productScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="环境卫生评分" prop="environmentScore">
            <el-slider
              v-model="ratingForm.environmentScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="价格合理性" prop="priceScore">
            <el-slider
              v-model="ratingForm.priceScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="调整原因" prop="reason">
            <el-input
              type="textarea"
              v-model="ratingForm.reason"
              :rows="3"
              placeholder="请输入调整原因"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 警告对话框 -->
    <el-dialog v-model="warningDialogVisible" title="发送警告" width="500px">
      <el-form
        ref="warningFormRef"
        :model="warningForm"
        :rules="warningFormRules"
        label-width="100px"
      >
        <el-form-item label="警告类型" prop="type">
          <el-select v-model="warningForm.type" placeholder="请选择警告类型">
            <el-option label="服务质量问题" value="service" />
            <el-option label="商品质量问题" value="product" />
            <el-option label="卫生问题" value="hygiene" />
            <el-option label="价格问题" value="price" />
            <el-option label="虚假宣传" value="false_advertising" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="警告内容" prop="content">
          <el-input
            type="textarea"
            v-model="warningForm.content"
            :rows="4"
            placeholder="请输入警告内容"
          />
        </el-form-item>
        <el-form-item label="整改期限" prop="deadline">
          <el-date-picker
            v-model="warningForm.deadline"
            type="date"
            placeholder="请选择整改期限"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warningDialogVisible = false">取消</el-button>
          <el-button type="warning" @click="submitWarning">发送警告</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处罚对话框 -->
    <el-dialog v-model="punishmentDialogVisible" title="商家处罚" width="500px">
      <el-form
        ref="punishmentFormRef"
        :model="punishmentForm"
        :rules="punishmentFormRules"
        label-width="100px"
      >
        <el-form-item label="处罚类型" prop="type">
          <el-select v-model="punishmentForm.type" placeholder="请选择处罚类型">
            <el-option label="警告" value="warning" />
            <el-option label="罚款" value="fine" />
            <el-option label="限制经营" value="restriction" />
            <el-option label="暂停经营" value="suspension" />
            <el-option label="终止合作" value="termination" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="罚款金额"
          prop="amount"
          v-if="punishmentForm.type === 'fine'"
        >
          <el-input-number
            v-model="punishmentForm.amount"
            :min="0"
            :step="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item
          label="处罚期限"
          prop="duration"
          v-if="['restriction', 'suspension'].includes(punishmentForm.type)"
        >
          <el-input-number
            v-model="punishmentForm.duration"
            :min="1"
            :step="1"
            controls-position="right"
          >
            <template #suffix>天</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="处罚原因" prop="reason">
          <el-input
            type="textarea"
            v-model="punishmentForm.reason"
            :rows="4"
            placeholder="请输入处罚原因"
          />
        </el-form-item>
        <el-form-item label="处罚说明" prop="description">
          <el-input
            type="textarea"
            v-model="punishmentForm.description"
            :rows="4"
            placeholder="请输入处罚说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="punishmentDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitPunishment"
            >确定处罚</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// 搜索表单
const searchForm = reactive({
  name: "",
  type: "",
  creditLevel: "",
});

// 列表数据
const loading = ref(false);
const sortOrder = ref("desc");
const merchantList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 统计数据
const ratingStats = ref([
  {
    label: "平均评分",
    value: "4.5",
    icon: "fas fa-star",
    color: "#ffd700",
  },
  {
    label: "优秀商家",
    value: "128",
    icon: "fas fa-crown",
    color: "#ff9900",
  },
  {
    label: "警告商家",
    value: "12",
    icon: "fas fa-exclamation-triangle",
    color: "#ff4949",
  },
  {
    label: "待整改",
    value: "5",
    icon: "fas fa-tools",
    color: "#409eff",
  },
]);

// 评分相关
const ratingDialogVisible = ref(false);
const ratingFormRef = ref(null);
const ratingForm = reactive({
  serviceScore: 0,
  productScore: 0,
  environmentScore: 0,
  priceScore: 0,
  reason: "",
  merchantId: "",
});

const ratingFormRules = {
  reason: [{ required: true, message: "请输入调整原因", trigger: "blur" }],
};

// 警告相关
const warningDialogVisible = ref(false);
const warningFormRef = ref(null);
const warningForm = reactive({
  type: "",
  content: "",
  deadline: "",
  merchantId: "",
});

const warningFormRules = {
  type: [{ required: true, message: "请选择警告类型", trigger: "change" }],
  content: [{ required: true, message: "请输入警告内容", trigger: "blur" }],
  deadline: [{ required: true, message: "请选择整改期限", trigger: "change" }],
};

// 处罚相关
const punishmentDialogVisible = ref(false);
const punishmentFormRef = ref(null);
const punishmentForm = reactive({
  type: "",
  amount: 0,
  duration: 1,
  reason: "",
  description: "",
  merchantId: "",
});

const punishmentFormRules = {
  type: [{ required: true, message: "请选择处罚类型", trigger: "change" }],
  amount: [{ required: true, message: "请输入罚款金额", trigger: "blur" }],
  duration: [{ required: true, message: "请输入处罚期限", trigger: "blur" }],
  reason: [{ required: true, message: "请输入处罚原因", trigger: "blur" }],
  description: [{ required: true, message: "请输入处罚说明", trigger: "blur" }],
};

// 获取商家列表
const fetchMerchantList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {};
    if (searchForm.name) params.merchantName = searchForm.name;
    if (searchForm.type) params.type = searchForm.type;
    if (searchForm.creditLevel) params.creditLevel = searchForm.creditLevel;
    params.page = currentPage.value;
    params.size = pageSize.value;
    params.sort = sortOrder.value;
    
    const response = await service.get('/admin/merchants/ratings', { params });
    
    if (response.code === 200) {
      merchantList.value = response.data.list || [];
      total.value = response.data.total || 0;
      
      // 更新统计数据
      const statsData = response.data.statistics || {};
      ratingStats.value = [
        {
          label: "平均评分",
          value: statsData.avgScore || "0",
          icon: "fas fa-star",
          color: "#ffd700",
        },
        {
          label: "优秀商家",
          value: statsData.excellentCount || "0",
          icon: "fas fa-crown",
          color: "#ff9900",
        },
        {
          label: "警告商家",
          value: statsData.warningCount || "0",
          icon: "fas fa-exclamation-triangle",
          color: "#ff4949",
        },
        {
          label: "待整改",
          value: statsData.needImproveCount || "0",
          icon: "fas fa-tools",
          color: "#409eff",
        },
      ];
    } else {
      // 使用测试数据
      // 模拟测试数据
      const mockData = [
        {
          id: 1,
          name: "阳朔西街小吃店",
          type: "restaurant",
          overallScore: 4.8,
          creditScore: 95,
          creditLevel: "excellent",
          warningCount: 0,
          complaintRate: 0.5,
          serviceScore: 96,
          productScore: 94,
          environmentScore: 98,
          priceScore: 92,
          userRating: 95,
        },
        {
          id: 2,
          name: "象鼻山景区",
          type: "scenic",
          overallScore: 4.2,
          creditScore: 85,
          creditLevel: "good",
          warningCount: 1,
          complaintRate: 2.1,
          serviceScore: 86,
          productScore: 88,
          environmentScore: 82,
          priceScore: 90,
          userRating: 85,
        },
        {
          id: 3,
          name: "桂林特产商店",
          type: "shopping",
          overallScore: 4.5,
          creditScore: 88,
          creditLevel: "good",
          warningCount: 0,
          complaintRate: 1.2,
          serviceScore: 89,
          productScore: 87,
          environmentScore: 92,
          priceScore: 85,
          userRating: 90,
        },
        {
          id: 4,
          name: "漓江渔火餐厅",
          type: "restaurant",
          overallScore: 3.5,
          creditScore: 65,
          creditLevel: "poor",
          warningCount: 3,
          complaintRate: 5.8,
          serviceScore: 65,
          productScore: 70,
          environmentScore: 75,
          priceScore: 60,
          userRating: 68,
        },
        {
          id: 5,
          name: "七星公园",
          type: "scenic",
          overallScore: 4.0,
          creditScore: 78,
          creditLevel: "normal",
          warningCount: 2,
          complaintRate: 3.2,
          serviceScore: 80,
          productScore: 82,
          environmentScore: 75,
          priceScore: 78,
          userRating: 79,
        },
        {
          id: 6,
          name: "独秀峰景区",
          type: "scenic",
          overallScore: 4.7,
          creditScore: 92,
          creditLevel: "excellent",
          warningCount: 0,
          complaintRate: 0.8,
          serviceScore: 93,
          productScore: 90,
          environmentScore: 95,
          priceScore: 88,
          userRating: 92,
        },
        {
          id: 7,
          name: "叠彩山夜市",
          type: "shopping",
          overallScore: 3.2,
          creditScore: 55,
          creditLevel: "risk",
          warningCount: 5,
          complaintRate: 8.5,
          serviceScore: 55,
          productScore: 60,
          environmentScore: 50,
          priceScore: 65,
          userRating: 58,
        },
        {
          id: 8,
          name: "桂林米粉店",
          type: "restaurant",
          overallScore: 4.3,
          creditScore: 86,
          creditLevel: "good",
          warningCount: 1,
          complaintRate: 1.8,
          serviceScore: 87,
          productScore: 85,
          environmentScore: 88,
          priceScore: 84,
          userRating: 86,
        },
      ];

      // 根据搜索条件筛选数据
      let filteredData = mockData.filter((item) => {
        let match = true;
        if (searchForm.name) {
          match = match && item.name.includes(searchForm.name);
        }
        if (searchForm.type) {
          match = match && item.type === searchForm.type;
        }
        if (searchForm.creditLevel) {
          match = match && item.creditLevel === searchForm.creditLevel;
        }
        return match;
      });

      // 分页处理
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      merchantList.value = filteredData.slice(start, end);
      total.value = filteredData.length;

      // 如果有排序，则进行排序
      if (sortOrder.value) {
        sortMerchantList();
      }

      // 更新统计数据
      const excellentCount = filteredData.filter(
        (item) => item.creditLevel === "excellent",
      ).length;
      const warningCount = filteredData.filter(
        (item) => item.warningCount > 0,
      ).length;
      const needImproveCount = filteredData.filter((item) =>
        ["poor", "risk"].includes(item.creditLevel),
      ).length;
      const avgScore = (
        filteredData.reduce((sum, item) => sum + item.overallScore, 0) /
        filteredData.length
      ).toFixed(1);

      ratingStats.value = [
        {
          label: "平均评分",
          value: avgScore,
          icon: "fas fa-star",
          color: "#ffd700",
        },
        {
          label: "优秀商家",
          value: excellentCount,
          icon: "fas fa-crown",
          color: "#ff9900",
        },
        {
          label: "警告商家",
          value: warningCount,
          icon: "fas fa-exclamation-triangle",
          color: "#ff4949",
        },
        {
          label: "待整改",
          value: needImproveCount,
          icon: "fas fa-tools",
          color: "#409eff",
        },
      ];
    }
  } catch (error) {
    console.error("获取商家列表失败：", error);
    ElMessage.error("获取商家列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchMerchantList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: "",
    type: "",
    creditLevel: "",
  });
  handleSearch();
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchMerchantList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchMerchantList();
};

// 获取评分颜色
const getScoreColor = (score) => {
  if (score >= 90) return "#67c23a";
  if (score >= 80) return "#409eff";
  if (score >= 60) return "#e6a23c";
  return "#f56c6c";
};

// 获取信用评分颜色
const getCreditScoreColor = (score) => {
  if (score >= 90) return "#67c23a";
  if (score >= 80) return "#409eff";
  if (score >= 60) return "#e6a23c";
  return "#f56c6c";
};

// 获取信用等级标签类型
const getCreditLevelTag = (level) => {
  const typeMap = {
    excellent: "success",
    good: "primary",
    normal: "",
    poor: "warning",
    risk: "danger",
  };
  return typeMap[level];
};

// 获取信用等级标签文本
const getCreditLevelLabel = (level) => {
  const labelMap = {
    excellent: "优秀",
    good: "良好",
    normal: "一般",
    poor: "较差",
    risk: "风险",
  };
  return labelMap[level];
};

// 获取商家类型标签类型
const getMerchantTypeTag = (type) => {
  const typeMap = {
    hotel: "success",
    restaurant: "warning",
    scenic: "primary",
    shopping: "info",
  };
  return typeMap[type];
};

// 获取商家类型标签文本
const getMerchantTypeLabel = (type) => {
  const labelMap = {
    hotel: "酒店",
    restaurant: "餐饮",
    scenic: "景点",
    shopping: "购物",
  };
  return labelMap[type];
};

// 评分调整
const handleRating = (row) => {
  Object.assign(ratingForm, {
    serviceScore: row.serviceScore,
    productScore: row.productScore,
    environmentScore: row.environmentScore,
    priceScore: row.priceScore,
    reason: "",
    merchantId: row.id,
  });
  ratingDialogVisible.value = true;
};

// 提交评分调整
const submitRating = async () => {
  if (!ratingFormRef.value) return;
  await ratingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const response = await service.post(`/admin/merchants/${ratingForm.merchantId}/adjust-rating`, {
          serviceScore: ratingForm.serviceScore,
          productScore: ratingForm.productScore,
          environmentScore: ratingForm.environmentScore,
          priceScore: ratingForm.priceScore,
          reason: ratingForm.reason
        });
        
        if (response.code === 200) {
          ElMessage.success("评分调整成功");
          ratingDialogVisible.value = false;
          fetchMerchantList();
        } else {
          ElMessage.error(response.message || "评分调整失败");
        }
      } catch (error) {
        console.error("评分调整失败：", error);
        ElMessage.error("评分调整失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 发送警告
const handleWarning = (row) => {
  Object.assign(warningForm, {
    type: "",
    content: "",
    deadline: "",
    merchantId: row.id
  });
  warningDialogVisible.value = true;
};

// 提交警告
const submitWarning = async () => {
  if (!warningFormRef.value) return;
  await warningFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const response = await service.post(`/admin/merchants/${warningForm.merchantId}/warning`, {
          type: warningForm.type,
          content: warningForm.content,
          deadline: warningForm.deadline
        });
        
        if (response.code === 200) {
          ElMessage.success("警告发送成功");
          warningDialogVisible.value = false;
          fetchMerchantList();
        } else {
          ElMessage.error(response.message || "警告发送失败");
        }
      } catch (error) {
        console.error("警告发送失败：", error);
        ElMessage.error("警告发送失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 处罚
const handlePunishment = (row) => {
  Object.assign(punishmentForm, {
    type: "",
    amount: 0,
    duration: 1,
    reason: "",
    description: "",
    merchantId: row.id
  });
  punishmentDialogVisible.value = true;
};

// 提交处罚
const submitPunishment = async () => {
  if (!punishmentFormRef.value) return;
  await punishmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const requestData = {
          type: punishmentForm.type,
          reason: punishmentForm.reason,
          description: punishmentForm.description
        };
        
        if (punishmentForm.type === 'fine') {
          requestData.amount = punishmentForm.amount;
        } else if (['restriction', 'suspension'].includes(punishmentForm.type)) {
          requestData.duration = punishmentForm.duration;
        }
        
        const response = await service.post(`/admin/merchants/${punishmentForm.merchantId}/punishment`, requestData);
        
        if (response.code === 200) {
          ElMessage.success("处罚提交成功");
          punishmentDialogVisible.value = false;
          fetchMerchantList();
        } else {
          ElMessage.error(response.message || "处罚提交失败");
        }
      } catch (error) {
        console.error("处罚提交失败：", error);
        ElMessage.error("处罚提交失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 切换排序顺序
const toggleSortOrder = (order) => {
  sortOrder.value = order;
  sortMerchantList();
};

// 排序商家列表
const sortMerchantList = () => {
  merchantList.value.sort((a, b) => {
    const factor = sortOrder.value === "asc" ? 1 : -1;
    return (a.creditScore - b.creditScore) * factor;
  });
};

// 导出评分数据
const exportRatings = () => {
  try {
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 准备导出数据
    const exportData = merchantList.value.map(item => ({
      '商家ID': item.id,
      '商家名称': item.name,
      '商家类型': getMerchantTypeLabel(item.type),
      '综合评分': item.overallScore,
      '信用评分': item.creditScore,
      '信用等级': getCreditLevelLabel(item.creditLevel),
      '警告次数': item.warningCount,
      '投诉率': `${item.complaintRate}%`,
      '服务质量评分': item.serviceScore,
      '商品质量评分': item.productScore,
      '环境卫生评分': item.environmentScore,
      '价格合理性': item.priceScore,
      '用户好评率': `${item.userRating}%`
    }));
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },  // 商家ID
      { wch: 20 }, // 商家名称
      { wch: 10 }, // 商家类型
      { wch: 10 }, // 综合评分
      { wch: 10 }, // 信用评分
      { wch: 10 }, // 信用等级
      { wch: 10 }, // 警告次数
      { wch: 10 }, // 投诉率
      { wch: 15 }, // 服务质量评分
      { wch: 15 }, // 商品质量评分
      { wch: 15 }, // 环境卫生评分
      { wch: 15 }, // 价格合理性
      { wch: 15 }  // 用户好评率
    ];
    ws['!cols'] = colWidths;
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "商家评分与信用数据");
    
    // 导出Excel
    XLSX.writeFile(wb, `商家评分与信用数据_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败");
  }
};

// 初始化
fetchMerchantList();
</script>

<style scoped>
.merchant-rating {
  padding: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px 0;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-light);
  transition: all 0.3s;
}

.statistics-content {
  display: flex;
  align-items: center;
}

.statistics-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.statistics-icon i {
  color: var(--el-color-white);
  font-size: 24px;
}

.statistics-info {
  flex: 1;
}

.statistics-info .label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.statistics-info .value {
  font-size: 24px;
  font-weight: 600;
  margin-top: 4px;
  color: var(--el-text-color-primary);
}

.table-header-operations {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 8px 0;
}

.table-header-operations .el-button {
  background-color: var(--el-button-bg-color);
  border-color: var(--el-border-color);
  color: var(--el-text-color-regular);
}

.table-header-operations .el-button.el-button--primary {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: var(--el-color-white);
}

.merchant-rating :deep(.el-dialog) {
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color);
}

.merchant-rating :deep(.el-dialog .el-dialog__header) {
  border-bottom: 1px solid var(--el-border-color-light);
}

.merchant-rating :deep(.el-dialog .el-dialog__body) {
  padding-top: 10px;
  color: var(--el-text-color-primary);
}

.merchant-rating :deep(.el-dialog .el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-light);
}

.merchant-rating :deep(.el-table) {
  background-color: var(--el-bg-color);
}

.merchant-rating :deep(.el-table th.el-table__cell) {
  background-color: var(--el-bg-color-overlay);
}

.merchant-rating :deep(.el-table .el-table__row) {
  background-color: var(--el-bg-color);
}

.merchant-rating :deep(.el-table .el-table__row:hover > td.el-table__cell) {
  background-color: var(--el-bg-color-overlay);
}

.rule-detail {
  padding: 20px;
  background-color: var(--el-bg-color-overlay);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.merchant-rating :deep(.rating-dialog .el-dialog__body) {
  padding: 0 20px;
  max-height: calc(90vh - 120px);
  overflow: hidden;
}

.merchant-rating :deep(.el-dialog__wrapper) {
  overflow: hidden;
}

.merchant-rating :deep(.el-overlay) {
  overflow: hidden;
}

/* 添加空状态样式与其他页面保持一致 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.form-header {
  margin-bottom: 15px;
}

.form-header .title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.form-footer {
  margin-top: 15px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
